package com.code2roc.jarmanage.filter;

import com.code2roc.jarmanage.util.Base64Util;
import com.code2roc.jarmanage.util.ConfigUtil;
import com.code2roc.jarmanage.util.ConvertUtil;
import com.code2roc.jarmanage.util.StringUtil;

import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        String authorization = ConvertUtil.convert2String(request.getHeader("Authorization"));
        boolean authPass = false;
        if (!StringUtil.isEmpty(authorization)) {
            String credentials = authorization.substring("Basic ".length());
            byte[] decodedCredentials = Base64Util.decode(credentials.getBytes("UTF-8"));
            String realcredentials = new String(decodedCredentials);
            String settingAuth = ConfigUtil.getConfigValue("username") + ":" + ConfigUtil.getConfigValue("password");
            if (settingAuth.equals(realcredentials)) {
                authPass = true;
            }
        }
        if(authPass){
            Cookie cookie = new Cookie("jarmanage-contextPath", ConfigUtil.getConfigValue("contextpath"));
            cookie.setMaxAge(2147483647);
            response.addCookie(cookie);
            filterChain.doFilter(servletRequest, servletResponse);
        }else{
            response.setStatus(401);
            response.setHeader("WWW-Authenticate", "Basic realm=\"Realm\"");
        }

    }

    public void destroy() {

    }
}
